package com.dw.etl.core.db;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author: zhangyao
 * @create:2020-04-07 11:20
 **/
@Aspect
@Component
public class DataSourceAop {

    @Pointcut("@annotation(com.dw.etl.core.db.RoutingDataSource)")
    public void routingDataSourcePointcut() {
    }

     /*@Around("routingDataSourcePointcut()")
   public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RoutingDataSource routerDataSource = method.getAnnotation(RoutingDataSource.class);
        if(CommonConstant.TRUE.equals(routerDataSource.haveIdDb())) {
            //joinPoint.get
            Field f = joinPoint.getTarget().getClass().getDeclaredField("idDbTar");//获取属性-->Field
            f.setAccessible(true);//如果是私有的 先要设置可访问
            String localSourceKey = (String) f.get(joinPoint.getTarget());
            ThreadLocalDataSource.setLocalSource(localSourceKey);
        }
        try {
            return joinPoint.proceed();
        } finally {
            ThreadLocalDataSource.setLocalSource(DataSourceConfig.DEFAULT_DATABASE);
        }
    }*/

    @After("routingDataSourcePointcut()")
    public void afterAspect(){
        ThreadLocalDataSource.setLocalSource(DataSourceConfig.DEFAULT_DATABASE);
    }
}
